<template>
  <div class="app-container" style="grid-template-columns: auto;">
    <div class="topToolbar">
      <div class="searchBar">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item prop="unit">
            <el-input
              v-model="queryParams.unit"
              placeholder="请输入对接单位"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="projectName">
            <el-input
              v-model="queryParams.projectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="projectStartDate">
            <el-date-picker clearable
                            v-model="queryParams.projectStartDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择项目开始日期"
                            @change="dateContrast('queryParams', 1)">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="projectEndDate">
            <el-date-picker clearable
                            v-model="queryParams.projectEndDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择项目结束日期"
                            @change="dateContrast('queryParams')">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="ActionBar" style="min-width: 90px;">
        <el-button icon="el-icon-refresh-right" @click="$tab.refreshPage($route);"></el-button>
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['project:info:add']">新增
        </el-button>
        <el-button plain icon="el-icon-edit" size="mini" @click="handleUpdate"
                   v-hasPermi="['project:info:edit']">修改
        </el-button>
        <el-button plain icon="el-icon-delete" size="mini" @click="handleDelete"
                   v-hasPermi="['project:info:remove']">删除
        </el-button>
        <!--        <el-button plain icon="el-icon-download" size="mini"-->
        <!--                   @click="handleExport" v-hasPermi="['project:info:export']">导出-->
        <!--        </el-button>-->
      </div>
    </div>

    <div class="main">
      <div class="main2">

        <div class="ToolBar">
          <div class="modNameBox">
            <div class="lump"></div>
            <span>项目管理-列表</span>
          </div>
          <el-button-group>
          </el-button-group>
        </div>

        <div class="mainContent">
          <div id="PrintMainTable" ref="PrintMainTable" style="height: calc(100% - 87px);margin-top: 20px; ">
            <el-table v-loading="loading" border element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                      :data="infoList" @selection-change="handleSelectionChange"
                      :row-style="tableRowStyle">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column type="index" width="50" label="序号">
                <template slot-scope="scope">
                  <span v-text="indexMethods(scope.$index)"></span>
                </template>
              </el-table-column>
              <el-table-column label="对接单位" width="200" align="center" prop="unit" :show-overflow-tooltip="true"/>
              <el-table-column label="对接单位详细地址" align="center" prop="address" :show-overflow-tooltip="true"/>
              <el-table-column label="对接人" width="80" align="center" prop="recepter" :show-overflow-tooltip="true"/>
              <el-table-column label="对接人部门职位" align="center" prop="deptPost" :show-overflow-tooltip="true"/>
              <el-table-column label="对接人联系方式" align="center" prop="phone" :show-overflow-tooltip="true"/>
              <el-table-column label="项目名称" align="center" prop="projectName" :show-overflow-tooltip="true"/>
              <el-table-column label="项目类型" width="60" align="center" prop="projectType">
                <span slot-scope="scope">
                  <dict-tag :options="dict.type.project_type" :value="scope.row.projectType"/>
                </span>
              </el-table-column>
              <el-table-column label="介绍人" width="80" align="center" prop="introducer" :show-overflow-tooltip="true"/>
              <el-table-column prop="geo" width="80" label="总负责人">
                <span slot-scope="scope">
                  {{ getUserName(scope.row.geo) }}
                </span>
              </el-table-column>
              <el-table-column label="项目预算" align="center" prop="projectBudget" width="80"/>
              <el-table-column label="项目开始日期" align="center" prop="projectStartDate" width="120">
                <span slot-scope="scope">
                  <span>{{ parseTime(scope.row.projectStartDate, '{y}-{m}-{d}') }}</span>
                </span>
              </el-table-column>
              <el-table-column label="项目结束日期" align="center" prop="projectEndDate" width="120">
                <span slot-scope="scope">
                  <span>{{ parseTime(scope.row.projectEndDate, '{y}-{m}-{d}') }}</span>
                </span>
              </el-table-column>
              <!--              <el-table-column label="项目阶段" width="120" align="center" prop="projectStep">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <dict-tag :options="dict.type.project_step" :value="scope.row.projectStep"/>-->
              <!--                </template>-->
              <!--              </el-table-column>-->

              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <span slot-scope="scope">

                  <!--根据项目类型不同跳转到不同的页面?-->
                  <div class="link-type">
                    <span v-hasPermi="['project:info:view']"
                          @click="redirectToProject(scope.row.projectId, scope.row.projectType,scope.row.projectName)">查看</span>
                  </div>



                </span>
              </el-table-column>

            </el-table>
          </div>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList"
                      :page-sizes="[10, 20, 30, 40, 50, 1000]"/>
        </div>

      </div>
    </div>

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="1050px" append-to-body
               class="dialogStyle el-dialog__body">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px"
               style="display: grid;grid-template-columns: 1fr 1fr 1fr;grid-column-gap: 15px; grid-row-gap: 10px;">
        <el-form-item label="对接单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入对接单位"/>
        </el-form-item>
        <el-form-item label="单位详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入单位详细地址"/>
        </el-form-item>
        <div v-for="(row, index) in rows" :key="index"
             style="position: relative; display: flex;grid-column: span 3;justify-content: space-between;">
          <i v-if="index == 0" class="el-icon-circle-plus-outline"
             style="position: absolute; right: -40px; top: 50%; transform: translateY(-85%); color: #1890FF; font-size: 30px; cursor: pointer;"
             @click="addRow"></i>
          <i v-else class="el-icon-circle-close"
             style="position: absolute; right: -40px; top: 50%; transform: translateY(-85%); color: #F56C6C; font-size: 30px; cursor: pointer;"
             @click="deleteRow(index)"></i>
          <el-form-item :label="'对接人 '">
            <el-input v-model="row.recepter" placeholder="请输入对接人"/>
          </el-form-item>
          <el-form-item :label="'对接人部门职位 '">
            <el-input v-model="row.deptPost" placeholder="请输入对接人部门职位"/>
          </el-form-item>
          <el-form-item :label="'对接人联系方式 '">
            <div style="display: flex; align-items: center;">
              <el-input v-model="row.phone" placeholder="对接人联系方式"/>
            </div>
          </el-form-item>
        </div>

        <el-form-item label="项目类型" prop="projectType" style="grid-column: span 1;">
          <el-select v-model="form.projectType" placeholder="请选择项目类型" clearable>
            <el-option
              v-for="dict in dict.type.project_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="总负责人" prop="geo">
          <el-select filterable v-model="form.geo" clearable placeholder="请选择项目总负责人" @change="updateProjectUsers">
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目开始日期" prop="projectStartDate">
          <el-date-picker clearable
                          v-model="form.projectStartDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择项目开始日期"
                          @change="dateContrast('form', 1)"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目结束日期" prop="projectEndDate">
          <el-date-picker clearable
                          v-model="form.projectEndDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择项目结束日期"
                          @change="dateContrast('form')"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目人员">
          <!--collapse-tags-->
          <el-select filterable v-model="form.userIds" multiple placeholder="请选择相关员工" @change="handleUserIdsChange">
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="介绍人" prop="introducer">
          <el-input v-model="form.introducer" placeholder="请输入介绍人"/>
        </el-form-item>

        <el-form-item label="项目预算" prop="projectBudget">
          <el-input v-model="form.projectBudget" placeholder="请输入项目预算"/>
        </el-form-item>
        <!--        <div style="grid-column: span 2;">-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <!--        </div> style="border-bottom: 1px solid #DCDFE6;"-->

      </el-form>

      <div class="ActionBut">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  delInfo,
  addInfo,
  updateInfo
} from "@/api/project/info";


export default {
  name: "Info",
  dicts: ['feiju_user_type', 'project_type', 'project_step'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看页
      openSee: false,
      ///是否查看阶段页
      IsStageBeDisplay: false,
      //人员选项
      userOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        unit: null,
        projectName: null,
        projectStartDate: null,
        projectEndDate: null,
      },
      // 表单参数
      form: {
        deptPost: '',
        recepter: '',
        phone: ''
      },
      // 表单校验 对应表单prop
      rules: {
        unit: [
          {required: true, message: "对接单位不能为空", trigger: "blur"}
        ],
        projectName: [
          {required: true, message: "项目名称不能为空", trigger: "blur"}
        ],
        projectType: [
          {required: true, message: "项目类型不能为空", trigger: "blur"}
        ],
        geo: [
          {required: true, message: "总负责人不能为空", trigger: "blur"}
        ],
        projectStartDate: [
          {required: true, message: "项目开始日期不能为空", trigger: "blur"}
        ],
        projectEndDate: [
          {required: true, message: "项目结束日期不能为空", trigger: "blur"}
        ],
      },
      dynamicRows: [],
      rows: [{
        //可以把每行三个字段分别加入三个数组、进而拼接成 带,的字符串存到form的字段中。回显可以反向操作
        deptPost: '',
        recepter: '',
        phone: ''
      }],// 存储动态添加的行数据
      deptPosts: [],
      recepters: [],
      phones: [],
      lastGeo: null,
      lastUserIds: []

    };
  },
  mounted() {
  },
  created() {
    this.getList();
    this.reset();
    getInfo().then(response => {
      this.userOptions = response.users;
    });
  },
  methods: {
    getUserName(userId) {
      const trimmedUserId = String(userId).trim();
      //注意在比较前还未对userOptions 赋值
      if (!this.userOptions || !Array.isArray(this.userOptions)) {
        return '';
      }
      const user = this.userOptions.find(user => String(user.userId).trim() === trimmedUserId);
      return user ? user.nickName : '';
    },
    redirectToProject(projectId, projectType, projectName) {
      if (projectType === 0) {
        this.$router.push({
          path: '/project/p-info/index/' + projectId,
          query: {projectName: projectName}
        });
      } else if (projectType === 1) {
        this.$router.push({path: '/project/p-zdyInfo/index/' + projectId});
      } else {
        //没有项目类型默认非居
        this.$router.push({path: '/project/p-info/index/' + projectId});
      }
    },
    updateProjectUsers() {
      if (this.lastGeo && this.lastGeo !== this.form.geo) {
        const index = this.form.userIds.findIndex(id => id === this.lastGeo);
        if (index >= 0) {
          this.form.userIds.splice(index, 1);
        }
      }
      if (this.form.geo && this.form.userIds.indexOf(this.form.geo) < 0) {
        this.form.userIds.push(this.form.geo);
      }
      this.lastGeo = this.form.geo;
      this.lastUserIds = [...this.form.userIds];
    },
    handleUserIdsChange() {
      const {userIds, geo} = this.form;
      if (geo != null && geo != '') {
        const exists = userIds.includes(geo);
        if (!exists) {
          userIds.push(geo);
        }
      }

    },
    addRow() {
      this.rows.push({
        deptPost: '',
        recepter: '',
        phone: ''
      });
    },
    deleteRow(index) {
      this.rows.splice(index, 1);
      // this.updateValidationRules();
    },
    //校验新增行
    // updateValidationRules() {
    //   this.rules.deptPost = [
    //     {required: true, message: '请输入对接人部门职位', trigger: 'blur'}
    //   ];
    //   this.rules.recepter = [
    //     {required: true, message: '请输入对接人', trigger: 'blur'}
    //   ];
    //   this.rules.phone = [
    //     {required: true, message: '请输入对接人联系方式', trigger: 'blur'}
    //   ];
    //   for (let i = 0; i < this.rows.length; i++) {
    //     const prefix = `rows[${i}].`;
    //     this.rules[prefix + 'deptPost'] = this.rules.deptPost;
    //     this.rules[prefix + 'recepter'] = this.rules.recepter;
    //     this.rules[prefix + 'phone'] = this.rules.phone;
    //   }
    // },
    /** 查询项目信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectName: null,
        unit: null,
        introducer: null,
        recepter: null,
        phone: null,
        projectBudget: null,
        projectStep: null,
        createTime: null,
        updateTime: null,
        remark: null,
        buildYear: null,
        projectStartDate: null,
        projectEndDate: null,
        projectType: null,
        address: null,
        deptPost: null,
        userType: null,
        userIds: [],
        geo: null
      };
      this.rows = [{
        //初始化
        deptPost: '',
        recepter: '',
        phone: ''
      }]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getInfo().then(response => {
        this.userOptions = response.users; //所有公司人员
        this.open = true;
        this.title = "项目新增";
      })

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (this.single) {
        this.$message({
          message: "一次只能修改一条！",
          type: "warning",
        });
        return false;
      }
      this.reset();
      const projectId = row.projectId || this.ids
      getInfo(projectId).then(response => {
        this.form = response.data;
        this.userOptions = response.users;
        this.$set(this.form, "userIds", response.userIds);

        const deptArray = this.form.deptPost == null ? '' : this.form.deptPost.split('、');
        const recepterArray = this.form.recepter == null ? '' : this.form.recepter.split('、');
        const phoneArray = this.form.phone == null ? '' : this.form.phone.split('、');

        var l = Math.max(deptArray.length, recepterArray.length, phoneArray.length) == 0 ? 1 : Math.max(deptArray.length, recepterArray.length, phoneArray.length);
        this.rows = [];

        for (let i = 0; i < l; i++) {
          const newRow = {};

          if (i < deptArray.length) {
            newRow.deptPost = deptArray[i];
          }

          if (i < recepterArray.length) {
            newRow.recepter = recepterArray[i];
          }

          if (i < phoneArray.length) {
            newRow.phone = phoneArray[i];
          }

          this.rows.push(newRow);
        }

        this.open = true;
        this.title = "项目修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let deptPosts = [];
      let recepters = [];
      let phones = [];

      for (let row of this.rows) {
        deptPosts.push(row.deptPost);
        recepters.push(row.recepter);
        phones.push(row.phone);
      }

      let deptPostString = deptPosts.join('、');
      let recepterString = recepters.join('、');
      let phoneString = phones.join('、');

      this.form.deptPost = deptPostString;
      this.form.recepter = recepterString;
      this.form.phone = phoneString;

      console.log("this.form=", this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      console.log("row.projectName=", row.projectName)
      if (this.ids.length == 0) {
        this.$message({
          message: "请选择一条消息！",
          type: "warning",
        });
        return false;
      }
      this.$modal.confirm("是否确认删除项目？").then(function () {
        return delInfo(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/info/export', {
        ...this.queryParams
      }, `项目管理${this.parseTime(new Date(), '{y}{m}{d}')}.xlsx`)
    },
    dateContrast(form, type) {
      if (new Date(this[form].projectStartDate) > new Date(this[form].projectEndDate)) {
        if (type) {
          this.$set(this[form], "projectEndDate", this[form].projectStartDate);
        } else {
          this.$set(this[form], "projectStartDate", this[form].projectEndDate);
        }
      }
    },
    //按钮变色
    changeColor(color) {
      this.bgColor = color;
      this.textColor = color === 'blue' ? 'white' : 'black';
    },
    // 分页连续序号
    indexMethods($index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
      );
    },
    // 行样式
    tableRowStyle({row, rowIndex}) {
      if (row.mergeFlag == 1) {
        return {
          background: "#FFDC7F",
        };
      }
      return {};
    },
  }
};
</script>

<style lang="scss" scoped>@import "~@/assets/styles/InspectionFrame.scss";</style>

<style lang="scss" scoped>
.app-container {
  .main {
    .main2 {
      .mainContent {
        .el-table {
          height: 100%;
          width: 100%;
        }
      }
    }
  }
}

.enablestatus {
  .dictRed {
    color: #f56c6c;
  }

  .dictBlue {
    color: #1890ff;
  }

  .dictGrey {
    color: #909399;
  }
}
</style>

<style>
.esri-ui-manual-container > .esri-component {
  display: none;
}
</style>
<style lang="scss" scoped>
@import "~@/assets/styles/InspectionFrame.scss";

.mapTitle {
  padding: 10px;
  //background-image: url("~@/assets/images/background.jpg");
}

.big {
  position: relative;
  width: 400px;
  height: 400px;
  margin: 0;
  padding: 0;

  #viewDiv {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
}

.buttons_Combine {
  display: flex;
  justify-content: flex-end;
}

.app-container {
  .main {
    .main2 {
      .mainContent {
        margin: 0;
        height: calc(100% - 46px);
        overflow: auto;

        ::v-deep.el-table--border .el-table__cell .cell {
          border-right: none;
          line-height: 23px;
          padding: 0;
        }

        ::v-deep.el-table {
          height: 100%;
        }

        ::v-deep.el-table__body-wrapper {
          height: calc(100% - 45px);
          overflow: auto;
        }

        ::v-deep.el-tag--medium {
          height: 23px;
          line-height: 23px;
        }
      }
    }

    ::v-deep.el-tabs--top {
      padding: 5px 10px;
      padding-top: 0;
    }

    .ToolBar {
      button {
        padding: 10px 10px;
      }
    }
  }

}

#PrintMainTable {
  overflow: auto;

  .el-table .caret-wrapper {
    height: 28px;

    .sort-caret.ascending {
      top: 3px;
    }

    .sort-caret.descending {
      bottom: 3px;
    }
  }
}

.closeButton {
  float: right;
  width: 72px;
  height: 36px;
  border: 1px solid rgba(220, 230, 230, 1);
  background-color: white;
  border-radius: 5px;
  user-select: none;
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* Internet Explorer/Edge */
  &:hover {
    background-color: rgba(220, 223, 230, 1);
  }
}
</style>

<style lang="scss">


</style>
